package com.cloud.rest;

import com.alibaba.fastjson.JSONObject;
import com.cloud.utils.BaseContextUtil;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

import static com.cloud.rest.EnumGlobalError.SUCCESS;
import static com.cloud.utils.GlobalMsgCodeConstant.TRACE_ID;


/**
 * 响应数据格式化
 * 只适用于名为soymilkadmin的前端项目
 *
 * @author yangyuwei
 * @create 2019-05-30
 */
@Data
@Accessors(chain = true)
@ApiModel(value = "响应格式类")
public class RestRes<T> implements Serializable {

    private static final long serialVersionUID = -8445943548965254778L;

    private String message;
    private T data;
    private String code;
    private String traceId;
    private String skyTraceId;

    public RestRes() {
        this.traceId = BaseContextUtil.get(TRACE_ID);
    }

    public RestRes(EnumGlobalError error) {
        this.code = error.getCode();
        this.message = error.getMsg();

    }

    public Boolean canSuccess() {
        return this.getCode().equals(SUCCESS.getCode());
    }

    /**
     * @Description: 格式化返回给前台的数据
     * @Author: tengyun
     * @Date: 2020-03-26
     * @Param data
     * @Return com.joyoung.cloud.common.msg.RestRes
     **/
    public static <T> RestRes apiData(T data) {
        RestRes restRes = new RestRes(SUCCESS);
        restRes.setData(data);
        return restRes;
    }

    /**
     * @param code    错误编码
     * @param message 错误信息
     * @return com.joyoung.cloud.common.msg.RestRes
     * @Description 格式化错误信息
     * @author yangyuwei on 2020/9/3 14:26
     **/
    public static RestRes<Boolean> errorData(String code, String message) {
        RestRes restRes = new RestRes();
        restRes.setCode(code).setMessage(message).setData(false);
        return restRes;
    }

    /**
     * @param user
     * @Description: 格式化获取token接口的响应参数, 返回前台需要的内容
     * @Author: tengyun
     * @Date: 2020-03-26
     * @Param token
     * @Return com.alibaba.fastjson.JSONObject
     **/
    public static <T> JSONObject token(String token, T user) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        jsonObject.put("user", user);
        return jsonObject;
    }


    /**
     * @param expires_in
     * @Description: 格式化获取appToken接口的响应参数, 返回前台需要的内容
     * @Author: tengyun
     * @Date: 2020-03-26
     * @Param token
     * @Return com.alibaba.fastjson.JSONObject
     **/
    public static JSONObject appToken(String token, int expires_in) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("access_token", token);
        jsonObject.put("expires_in", expires_in);
        //token类型为app
        jsonObject.put("type", "A");
        return jsonObject;
    }
}
